const express = require('express');
const router = express.Router();
const svgCaptcha=require("svg-captcha");
const sms_util=require("./../util/sms_util");
const conn=require('./../db/db');
const md5 = require('blueimp-md5');
//const multer=require('multer');
const formidable=require('formidable')
let path = require("path");
let fs = require("fs");
let users={};//保存用户信息

/*
* GET home page.
*/
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

/*
*图形验证码
 */
router.get('/api/captcha',(req,res)=>{
    let captcha = svgCaptcha.create({
        color:true,
        noise:2,
        ignoreChars: '0o1i',
        size: 4
    });
    /*console.log(captcha.text);*///得到的验证码
    
    //取出验证码保存到session中
    req.session.captcha=captcha.text.toLocaleLowerCase();
    //返回客户端
    res.type('svg');
    //显示在客户端页面
    res.send(captcha.data)
});

/*
*发送短信验证码 第三方短信接口
 */
/*router.get('/api/send_code',(req,res)=>{
    
    //获取手机号码
    let phoneNum=req.query.phone;
    
    //产生随机验证码
    let code=sms_util.randomCode(6);
    
    /!*console.log(code);  *!///手机号验证码
    
    setTimeout(()=>{
        //模拟用户获取验证码成功
        users[phoneNum]=code;
    
        //将成功的验证码返回出去
        res.json({success_code:200,message:code});
        
    },2000)
    
    //失败
    /!*setTimeout(()=>{
        res.json({err_code:0,message:'验证码获取失败'});
    },2000)*!/

    
    //实际短信验证码校验
   /!* sms_util.sendCode(phoneNum, code, function (success) {
        if(success){
            users[phoneNum]=code;
            res.json({success_code:200,message:'验证码获取成功'});
        }else{
            res.json({err_code:0,message:'验证码获取失败'});
        }
    })*!/
});*/

/*
*手机验证码登录
 */
/*router.post('/api/login_code',(req,res)=>{
   const phone=req.body.phone;
   const code=req.body.code;
    /!*res.json({err_code:0,message:{phone,code}});*!/
   
   //验证码是否与手机匹配
   if(users[phone]!==code){
       res.json({err_code:0,message:'验证码获取失败'});
       return;
   }
   
   //查询
    delete users[phone];
    let sqlStr="select * from pdd_user_info where user_phone='"+phone+"' limit 1";
    conn.query(sqlStr,(error,results,fiedls)=>{
        if(error){
            res.json({
                err_code:0,
                message:'请求数据失败'
            })
        }else{
            results=JSON.parse(JSON.stringify(results));
            if(results[0]){
                //用户已经存在
                req.session.userId=results[0].id;
                //返回数据给客户端
                res.json({
                    success_code:'200',
                    message:{
                        id:results[0].id,
                        user_name:results[0].user_name,
                        user_phone:results[0].user_phone
                    }
                });
            }else{
                //新用户  插入新用户数据
                let addSql="insert into pdd_user_info(user_name,user_phone) values (?,?)";
                let addSqlParams=[phone,phone];
                
                conn.query(addSql,addSqlParams,(error,results,fields)=>{
                    results=JSON.parse(JSON.stringify(results));
                    if(!error){
                       //继续查询
                        req.session.userId=results.insertId;
                        let sqlStr="select * from pdd_user_info where id='"+results.insertId+"' limit 1";
                        conn.query(sqlStr,(error,results,fields)=>{
                            if(error){
                                res.json({
                                    err_code:0,
                                    message:'请求数据失败'
                                })
                            }else{
                                results=JSON.parse(JSON.stringify(results));
                                res.json({
                                    success_code:'200',
                                    message:{
                                        id:results[0].id,
                                        user_name:results[0].user_name,
                                        user_phone:results[0].user_phone
                                    }
                                })
                            }
                        })
                    }else{
                    
                    }
                })
                
            }
            
        }
    })
   
});*/

/*
*用户名密码登录
 */
/*router.post('/api/login_pwd',(req,res)=>{
    const user_name=req.body.name;
    const user_pwd=md5(req.body.pwd);
    const captcha=req.body.captcha.toLowerCase();
    console.log(captcha,req.session);
    
    //判断图形验证码是否正确
    /!*if(captcha!=req.session.captcha){
        req.json({err_code:0,message:'验证码不正确'});
    }
    delete req.session.captcha;*!/
    
    //判断用户名和密码是否匹配  查询数据
  /!*  let sqlStr="select * from pdd_user_info where user_name='"+user_name+"' limit 1";
    conn.query(sqlStr,(error,results,fiedls)=>{
        if(error){
            res.json({
                err_code:0,
                message:'用户名不存在！'
            })
        }else{
            results=JSON.parse(JSON.stringify(results));
            if(results[0]){//用户已经存在
                //验证密码是否正确
                if(results[0].user_pwd!==user_pwd){
                    res.json({
                        err_code:0,
                        message:'密码不正确！'
                    })
                }else{
                    req.session.userId=results[0].id;
                    //返回数据给客户端
                    res.json({
                        success_code:'200',
                        message:{
                            id:results[0].id,
                            user_name:results[0].user_name,
                            user_phone:results[0].user_phone
                        }
                    })
                }
            }else{//新用户  插入新用户数据
                let addSql="insert into pdd_user_info(user_name,user_pwd) values (?,?)";
                let addSqlParams=[user_name,user_pwd];
                
                conn.query(addSql,addSqlParams,(error,results,fields)=>{
                    results=JSON.parse(JSON.stringify(results));
                    if(!error){
                        //继续查询
                        req.session.userId=results.insertId;
                        let sqlStr="select * from pdd_user_info where id='"+results.insertId+"' limit 1";
                        conn.query(sqlStr,(error,results,fields)=>{
                            if(error){
                                res.json({
                                    err_code:0,
                                    message:'请求数据失败'
                                })
                            }else{
                                results=JSON.parse(JSON.stringify(results));
                                res.json({
                                    success_code:'200',
                                    message:{
                                        id:results[0].id,
                                        user_name:results[0].user_name,
                                        user_phone:results[0].user_phone
                                    }
                                });
                            }
                        });
                    }
                });
            }
        }
    })*!/
});*/


/*
* 首页轮播图
*/
/*router.get('/api/homecasual',(req,res)=>{
    //数据库查询语句
    let sqlStr="select * from pdd_homecasual";
    //执行查询语句
    conn.query(sqlStr,(error,results,fiedls)=>{
        if(error){
            res.json({
                err_code:0,
                message:'请求数据失败'
            })
        }else{
            res.json({
                success_code:'200',
                message:results
            })
        }
    })
});*/

/*
  获取首页导航
 */
/*router.get('/api/buy_cart', (req, res)=>{
    //数据库查询语句
    let sqlStr="select * from lk_pdd_cart";
    //执行查询语句
    conn.query(sqlStr,(error,results,fiedls)=>{
        if(error){
            res.json({
                err_code:0,
                message:'请求数据失败'
            })
        }else{
            res.json({
                success_code:'200',
                message:results
            })
        }
    })
});*/

/*
 *推荐版块
 * 分页：当前页码，每页条数
 */
/*router.get('/api/recommend',(req,res)=>{
    //获取页面参数
    let pageNo=req.query.page||1;
    let pageSize=req.query.count||20;
    //数据库查询语句
    let sqlStr='select * from pdd_recommend limit '+(pageNo-1)*pageSize+','+pageSize;
    //执行查询语句
    conn.query(sqlStr,(error,results,fiedls)=>{
        if(error){
            res.json({
                err_code:0,
                message:'请求数据失败'
            })
        }else{
            res.json({
                success_code:'200',
                message:results
            })
        }
    })
});*/

/*
*根据session中用户的id获取用户信息
 */
/*router.get('/api/user_info',(res,req)=>{
    let userId=req.session.userId;
    
    //查询数据库
    let sqlStr="select * from pdd_user_info where id'"+userId+"' limit 1";
    conn.query(sqlStr,(error,results,fields)=>{
        if(error){
            
            res.json({err_code:0,message:'请求数据失败'})
        }else{
            results==JSON.parse(JSON.stringify(results));
            if(!results[0]){
                delete req.session.userId;
                res.json({
                    error_code:1,
                    message:'请先登录'
                })
            }else{
                //返回数据给客户端
                res.json({
                    success_code:200,
                    message:{
                        id:results[0].id,
                        user_name:results[0].user_name,
                        user_phone:results[0].user_phone
                    }
                })
            }
        }
    })
});*/

/*-------------------------------------------------------------------*/

/*
创建文章
 */
router.post('/api/create',(req,res)=>{
   let title=req.body.title;
   let content=req.body.content;
    console.log(title,content);
    
    let addSql="insert into artical(title,content) values(?,?)";
    let addPrames=[title,content];
    
    conn.query(addSql,addPrames,(error,result)=>{
        if(error){
            res.json({
                err_code:0,
                message:'数据插入失败'
            })
        }else{
            res.json({
                success_code:200,
                message:result
            })
        }
    })
});

/*
文章详情
 */
router.get('/api/artical/:id',(req,res)=>{
   let id=req.params.id;
   console.log(id);
   let strSql="select * from  artical where id="+id;
   conn.query(strSql,(error,result)=>{
       if(error){
           res.json({
               err_code:0,
               message:'请求数据失败'
           })
       }else{
           res.json({
               success_code:'200',
               message:result
           });
       }
   })
});

/*
修改文章
 */
router.post('/api/artical/:id',(req,res)=>{
    let id=req.params.id;
    let title=req.body.title;
    let content=req.body.content;
    let updateParams=[title,content];
    console.log(updateParams);
    console.log(title,content);
    let strSql="update artical set title=?,content=? where id="+id;
    
    conn.query(strSql,updateParams,(error,result)=>{
        if(error){
            res.json({
                err_code:0,
                message:'修改数据失败'
            })
        }else{
            res.json({
                success_code:'200',
                message:result
            })
        }
    })
});

/*
查询文章
 */
router.get('/api/getlist',(req,res)=>{
    let strSql="select * from  artical";
    conn.query(strSql,(error,result)=>{
        if(error){
            res.json({
               err_code:0,
               message:'请求数据失败'
            })
        }else{
            res.json({
                success_code:'200',
                message:result
            })
        }
    })
});

/*
删除文章
 */
router.delete('/api/remove/:id',(req,res)=>{
    let id=req.params.id;
    console.log(req.body);
    let strSql="delete from artical where id="+id;
    conn.query(strSql,(error,result)=>{
        if(error){
            res.json({
                err_code:0,
                message:'删除数据失败'
            });
        }else{
            res.json({
                success_code:'200',
                message:result
            })
        }
    })
});

/*-------------------------------------------------------------------*/

/*
*上传图片接口
*/

//上传的文件保存在 upload
router.post('/api/upload',(res,req,next)=>{
    
    let form = new formidable.IncomingForm();
    // 设置编码
    form.encoding = 'utf-8';
    // 保留后缀名
    //form.keepExtensions = true;
    // 设置存储路径
    form.uploadDir = "./public/images/";
   
    form.parse(req, function(err, fields, files) {
        if(err){
            console.log(err);
        }
        console.log("files:",files)  //这里能获取到图片的信息
        console.log("fields:",fields) //这里能获取到传的参数的信息，如上面的message参数，可以通过fields。message来得到
    })
  
});


module.exports = router;
